fromRight ? index-- : ++index < length
源碼
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
解析
fromRight ? index-- : ++index < length
/*
現在問題來了,這個三元表達式有兩種可能,一種是:
*/
(fromRight ? index-- : ++index) < length
/*
一種是:
*/
fromRight ? index-- : (++index < length)
/*
根據MDN表格優(yōu)先級
這個表將優(yōu)化級劃分成了20個級別,數字越大,優(yōu)化級越高。
從表中可以看到,比較運算符的優(yōu)先級為11,而三元表達式(條件運算符)的優(yōu)化級為4,
因此可以確定比較運算符的優(yōu)先級要比三元表達式的要高,循環(huán)條件其實等價于第二種寫法。
*/
array || (array = Array(length));
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
// 當傳入array的時候則跳過后面一步,如果沒有傳入,即!!array為false,則執(zhí)行后面異步,array被賦予新的值
array || (array = Array(length));
// 如果不是傳入數組會報錯嗎?答案是不會,并且同樣有進行賦值操作,同時不會報錯
while (++index < length) {
array[index] = source[index];
}
return array;
}
length = array == null ? 0 : array.length
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
// 三目表達式和賦值運算符:先三目后賦值
// 這樣可以對length的值進行正確的賦值
length = array == null ? 0 : array.length,
// 通過Array(length)來創(chuàng)建一個和源數組一樣長度的空數組
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}