Array

2018-04-13  本文已影响0人  李华炎

数组对象的方法

1-concat()

2-every()

3-filter()

//返回数组 ages 中所有元素都大于 18 的元素:
var ages = [32, 33, 16, 40];

function checkAdult(age) {
    return age >= 18;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}

//结果32,33,40

4-indexOf()

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");    //2

var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.indexOf("Apple",4);  //6

5-join()

//将数组中的所有元素输出为字符串,join()等同于join(','),默认就是用逗号分隔
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();             //Banana,Orange,Apple,Mango

//指定分隔符
var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.join(""));   // BananaOrangeAppleMango
var energy = fruits.join("-");      //Banana-Orange-Apple-Mango
var energy = fruits.join(" and ");  //Banana and Orange and Apple and Mango

6-lastIndexOf()

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");        //2

var fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
var a = fruits.lastIndexOf("Apple");        //6

7-map()

var numbers = [4, 9, 16, 25];
console.log(numbers.map(Math.sqrt)); // 2,3,4,5

8-pop();

9-push();

10-reverse()

11-shift()

12-slice()

13-some()

14-sort()

15-splice()

16-toString()

17-unshift()

18-valueOf()

面试题

// 1.在不改变原数组a = [1,2,3]的情况下,拷贝出数组b,并且数组a != b,请选择( BD )。
let b=a;                //A
let b = a.slice();      //B
let b = a.splice(0,0);  //C
let b = a.concat();     //D
// 2.将数组var a = [1,2,3]  变成数组 [4,3,2,1]下面方式正确的是?    ( AC )
a.reverse().unshift(4);
a.push(4).reverse();
a.push(4);a.reverse();
a.splice(3,1,4).reverse();
上一篇下一篇

猜你喜欢

热点阅读