Array

2017-08-26  本文已影响0人  白柏更好

数组方法里push、pop、shift、unshift、join、splice分别是什么作用?用 splice函数分别实现push、pop、shift、unshift方法

//push方法
var color = ["red", "black", "blue"];
color.splice(color.length, 0, "yellow")
console.log(color.push)  // ["red", "black", "blue", "yellow"]
//pop方法
var color = ["red", "black", "blue"];
color.splice(color.length-1,1)
console.log(color) // ["red", "black"]
//shift方法
var color = ["red", "black", "blue"];
color.splice(0,1)
console.log(color)   // ["black", "blue"]
//unshift方法
 var color = ["red", "black", "blue"];
color.splice(0,0,"yellow")
console.log(color)   // ["yellow", "red", "black", "blue"]

写一个函数,操作数组,数组中的每一项变为原来的平方,在原数组上操作

function squareArr(arr){
    for(var i=0; i<arr.length; i++) {
        arr[i]=Math.pow(arr[i],2)
    } return arr
}
var arr = [2, 4, 6]
console.log(squareArr(arr)) // [4, 16, 36]

写一个函数,操作数组,返回一个新数组,新数组中只包含正数,原数组不变

function filterPositive(arr){
    return arr.filter(function(element){
        return element>0 && typeof element=='number';
    })
}
var arr = [3, -1,  2,  '饥人谷', true]
var newArr = filterPositive(arr)
console.log(newArr) //[3, 2]
console.log(arr) //[3, -1,  2,  '饥人谷', true]
上一篇 下一篇

猜你喜欢

热点阅读