javascript array

forEach

var fruits = ["Apple", "Banana"];
fruits.forEach(function (item, index, array) {
  console.log(item, index);
});
// Apple 0
// Banana 1

filter 是过滤数组,return true false

function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

pop & shift 都是移除, push & unshift 都是添加

concat 串联可以多个数组一起,或深层串联

var alpha = ['a', 'b', 'c'];

var alphaNumeric = alpha.concat(1, [2, 3]);

console.log(alphaNumeric); 
// Result: ['a', 'b', 'c', 1, 2, 3]

every 每一个结果都是true 就返回true

some 是其中一个结果true 就返回true

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

lastIndexOf 可以找在数组中的位置,或确定指定位置有没有要找的对象同时同步资料

var array = [2, 5, 9, 2];
array.lastIndexOf(2);     // 3
array.lastIndexOf(7);     // -1
array.lastIndexOf(2, 3);  // 3
array.lastIndexOf(2, 2);  // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3

reduce 拿到现在的对象和之后的对象来做事

reduceRight 是右到左

var total = [0, 1, 2, 3].reduce(function(a, b) {
  return a + b;
},10);
// total == 16

reverse就是调转对象顺序

var myArray = ['one', 'two', 'three'];
myArray.reverse(); 

console.log(myArray) // ['three', 'two', 'one']

sort 排列,依据ASCII的排列,所以号码大小不会是顺序

slice 可以找到第几个位置,决定要移除几个,在决定要添加几个

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

toLocaleString 是把对象中的字全转成string

var number = 1337;
var date = new Date();
var myArr = [number, date, 'foo'];

var str = myArr.toLocaleString(); 

console.log(str); 
// logs '1337,6.12.2013 19:37:35,foo'

toString 转成可显示的string

var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];
var myVar = monthNames.toString(); // assigns 'Jan,Feb,Mar,Apr' to myVar.
原文地址:https://www.cnblogs.com/stooges/p/4931089.html