检查数组中的第一项是否为空值
Check if first item in array is empty value
我已经看到许多关于检查数组是否为空的问题。但是我找不到关于如何检查数组中的第一项是否为空的问题。
目前,我正在以这种方式进行检查,但我非常怀疑这是不是正确的方式。
var specialtiesListArray = ['', 'not', 'empty', 'value'];
if (specialtiesListArray[0] == '') {
specialtiesListArray.shift(); // <== Removing the first item when empty.
}
console.info({ specialtiesListArray });
以上工作正常,但我想知道这样可以吗?有没有更好的方法。如果有人知道副本,请告诉我。如果问题已经得到回答,我很乐意删除它。
您可以使用 filter
并更新数组。
specialtiesListArray = ['', 'not', 'empty', 'value'];
specialtiesListArray = specialtiesListArray.filter((item, index) => index!==0 && item !== '');
console.log(specialtiesListArray);
我觉得你的方法很好。您可以创建一个函数,并在尝试读取索引 0
:
处的元素之前检查数组长度
- utils.js
export const removeFirstItemIfEmpty = (array) => {
if (array.length > 0 && array[0] == '') {
array.shift();
}
return array;
}
import { removeFirstItemIfEmpty } from './utils.js'
const result = removeFirstItemIfEmpty(['', 'not', 'empty', 'value']);
console.info({ result });
以下函数将删除任何未定义的、空的或空的,但将允许数字 0
通过:
var testArr = [['', null, 'not', 'empty', 'value'],[false,2,3,4],[undefined,"", null,"one","two"],[0,1,2,3]];
function ltrimArr(arr){
while (arr.length && !arr[0]&&arr[0]!==0) arr.shift();
return arr
}
testArr.forEach(a=>console.log(ltrimArr(a)))
我已经看到许多关于检查数组是否为空的问题。但是我找不到关于如何检查数组中的第一项是否为空的问题。
目前,我正在以这种方式进行检查,但我非常怀疑这是不是正确的方式。
var specialtiesListArray = ['', 'not', 'empty', 'value'];
if (specialtiesListArray[0] == '') {
specialtiesListArray.shift(); // <== Removing the first item when empty.
}
console.info({ specialtiesListArray });
以上工作正常,但我想知道这样可以吗?有没有更好的方法。如果有人知道副本,请告诉我。如果问题已经得到回答,我很乐意删除它。
您可以使用 filter
并更新数组。
specialtiesListArray = ['', 'not', 'empty', 'value'];
specialtiesListArray = specialtiesListArray.filter((item, index) => index!==0 && item !== '');
console.log(specialtiesListArray);
我觉得你的方法很好。您可以创建一个函数,并在尝试读取索引 0
:
- utils.js
export const removeFirstItemIfEmpty = (array) => {
if (array.length > 0 && array[0] == '') {
array.shift();
}
return array;
}
import { removeFirstItemIfEmpty } from './utils.js'
const result = removeFirstItemIfEmpty(['', 'not', 'empty', 'value']);
console.info({ result });
以下函数将删除任何未定义的、空的或空的,但将允许数字 0
通过:
var testArr = [['', null, 'not', 'empty', 'value'],[false,2,3,4],[undefined,"", null,"one","two"],[0,1,2,3]];
function ltrimArr(arr){
while (arr.length && !arr[0]&&arr[0]!==0) arr.shift();
return arr
}
testArr.forEach(a=>console.log(ltrimArr(a)))