lodash 函數庫- - compack函數

compack函數

建立一個新數組,包含原數組中全部的非假值元素。
例如false, null,0, "", undefined, 和 NaN 都是被認爲是「假值」。html

通常用於過濾數組中的假值typescript

在定義返回類型時候,採用Exclude條件類型把nullundefiendfalse0""、這幾種值排除掉.數組

/**
 *
 * 建立一個新數組,包含原數組中全部的非假值元素。
 * 例如false, null,0, "", undefined, 和 NaN 都是被認爲是「假值」。
 *
 *
 * @param array 待處理數組
 * @returns ${Array} 返回過濾掉假值的新數組
 * @example
 *
 * compack(['1',0,'',null,undefined,NaN])
 * // => ['1']
 */

const compack = <T>(array: Array<T>): Array<Exclude<T, null | undefined | false | 0 | "">> => {
	let result = new Array();
	// 邊界檢查與條件判斷
	for (let i = 0; i < array.length; i++) {
		if (array[i]) result.push(array[i]);
	}
	return result;
};

export default compack;

實用例子:

import compack from "../src/compack";

const arr = [0, , , "", 2, null, undefined, NaN, "s"];
const nw = compack(arr);
console.log(nw);  // [ 2, 's' ]

我的做品

ip定位查詢瀏覽器插件
老虎優惠券瀏覽器插件瀏覽器

相關文章
相關標籤/搜索