lodash源碼——運算符

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;
}
參考網址

https://segmentfault.com/a/1190000013133803

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容