js, jq traverse arrays and objects

js to traverse the array

1. Ordinary for loop

var arr = [1,4,45,34,12,45,56,8];
for ( var i = 0; i <arr.length; i++){
    console.log(arr[i]);
};

2. Optimized for loop: store the length of the array to avoid repeated acquisition of the length. The larger the array, the more obvious the optimization effect

var arr = [1,4,45,34,12,45,56,8];
var len = arr.length;
for ( var i = 0; i <len; i++){
    console.log(arr[i]);
};

3. Use for...in, but do not use for in in array traversal. This method is generally used for object traversal. The index variable type in the following example is string, not number.

var arr = [1,4,45,34,12,45,56,8];
for(var index in arr){
    console.log(typeof index);//string
    console.log(index+"--"+arr[index]); 
};

4. Use for...of, better performance

var arr = [1,4,45,34,12,45,56,8];
for(var value of arr){
    console.log(value);
};

5. Use forEach, with its own loop function

The disadvantage of the forEach loop is that you cannot use the break statement to interrupt the loop, nor can you use return to return to the outer function.

var arr = [1, 4, 45, 34, 12, 45, 56, 8];
arr.forEach(function (value, index) { // 第一参数是值,第二个参数是索引
    console.log(index + "--" + value);
});

6. Use map, which has the same syntax as forEach, and has better performance than forEach

The map traversal array method supports return and returns a new array.

var arr = [1, 4, 45, 34, 12, 45, 56, 8];
var newArr = arr.map(function (value, index) {// 第一参数是值,第二个参数是索引
    console.log(index + "--" + value);
    return value += 1;
});
console.log(newArr);// [2, 5, 46, 35, 13, 46, 57, 9]

js traversal object

1.for...in traversal

var obj = {
    name: "张三",
    age: 18,
    sex: "男"
};
for (var key in obj) {
    console.log(key+":"+obj[key]);
};

jq iterates over arrays and objects

1. $.each traverses the array

var arr = [1, 4, 45, 34, 12, 45, 56, 8];
$.each(arr, function (index, value) {//第一个参数是索引,第二个参数是值
    console.log(index + "--" + value);
});

2. $.each traverses objects

var obj = {
    name: "张三",
    age: 18,
    sex: "男"
};
$.each(obj, function (key, value) {//第一个参数是键,第二个参数是值
    console.log(key + ":" + value);
});

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/120254249