# 循环

# 方法

# for

  1. 只能遍历数组
  2. 缓存数组长度,但避免长度变化越界
  3. var 防止 i 及内部变量泄漏。es6 中  使用 let。
  4. continue 跳出本次循环,break 跳出总循环
(function() {
  //循环置于闭包之内
  for (let i = 0, length = array.length; i < length; i++) {
    //缓存数组长度
    console.log(array[i]); //内部方法若有可能相互影响,也要置于闭包之内
  }
})();

# while & do...while

TIP

判断执行次数,首先看 n 可能取值,再看限制条件 n: 0, 1, 2, 3, 4 ... condition: n < 3 res: 0, 1, 2

var n = 0;
var res = "";
while (n < 3) {
  n++;
  res += n
}
console.log(n); // expected output: 3
console.log(res) // 123

至少执行一次

var result = "";
var i = 0;

do {
  i = i + 1;
  result = result + i;
} while (i < 5);

console.log(result);
// expected result: "12345"
  1. continue [label]; 跳到指定标签 statement
var i = 0;
var j = 8;

checkiandj: while (i < 4) {
  console.log('i: ' + i);
  i += 1;

  checkj: while (j > 4) {
    console.log('j: ' + j);
    j -= 1;

    if ((j % 2) == 0)
      continue checkj;
    console.log(j + ' is odd.');
  }
  console.log('i = ' + i);
  console.log('j = ' + j);
}

# forEach

array.forEach((item, index, array) => {
  if(item=="囚徒")
    return;//这里只能使用return跳过当前元素处理
  console.log(item);
})
  1. return: undefined
  2. 无法中止循环,只能 return 跳出本次循环

# array.every() .some() .find() .findIndex() .includes()

Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

测试函数。

  • every()
function isBelowThreshold(element, index, array) {
  return element < 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
  • some()
function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
  • find() return: The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }
  • findIndex() The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

当测试条件为 true 时,findIndex() 返回索引位置,之后值不再调用函数。

var array1 = [5, 12, 8, 130, 44];

function isLargeNumber(element) {
  return element > 13;
}

console.log(array1.findIndex(isLargeNumber));
// expected output: 3
  • includes() arr.includes(valueToFind[, fromIndex])

::: info When comparing strings and characters, includes() is case-sensitive. :::

reutrn: ture or false

// array length is 3
// fromIndex is -100
// computed index is 3 + (-100) = -97

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

arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
arr.includes('a', -2); // false

// includes() used as a generic method
(function() {
  console.log([].includes.call(arguments, 'a')); // true
  console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');

# indexOf()

arr.indexOf(searchElement[, fromIndex])

The first index of the element in the array; -1 if not found.

与 findIndex() 区别,indexOf() 会从头到尾查找。

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(2, 1); // -1

# for...in

for (variable in object)
  statement

The for...in statement iterates over all non-Symbol, enumerable properties of an object.

可遍历带迭代器对象的可枚举属性。遍历数组时顺序可能不对。一般用作 debug。

::: info In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited.

Given that for...in is built for iterating object properties, not recommended for use with arrays, and options like Array.prototype.forEach() and for...of exist, what might be the use of for...in at all? :::

var obj = {a: 1, b: 2, c: 3};
    
for (const prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

// llustrates the use of hasOwnProperty():
var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (const prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(`obj.${prop} = ${obj[prop]}`);
  } 
}

// Output:
// "obj.color = red"

# for...of

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

The for...of statement iterates over values that the iterable object defines to be iterated over.

调用默认迭代器。

for (variable of iterable) {
  statement
}
// You can use let instead of const too, if you reassign the variable inside the block.

const iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}
// 11
// 21
// 31

# array.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.

::: info Signs you shouldn't be using map: A) You're not using the array it returns, and/or B) You're not returning a value from the callback. :::

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

# array.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

# array.from()

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

浅复制,Return A new Array instance.

Array.from(arrayLike[, mapFn[, thisArg]])

const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]

# array.reduce()

Return: The single value that results from the reduction.

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
var maxCallback2 = ( max, cur ) => Math.max( max, cur );

// reduce() without initialValue
[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
[                      ].reduce( maxCallback ); // TypeError

// map/reduce; better solution, also works for empty or larger arrays
[ { x: 22 }, { x: 42 } ].map( el => el.x )
                        .reduce( maxCallback2, -Infinity );
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]
  • 数组去重
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator
}, [])

console.log(myOrderedArray);

# $.each()

$.each(array|o, function(i, ele){}) 支持数组和对象

# 参考

Last Updated: 5/14/2022, 11:38:45 AM