我有一个数组,其元素由各种字符(数字和字母)组成。如何检查给定元素的第一个字符是否为数字?我试图使用拼接/切片但由于某种原因我无法得到解决方案。我有这样的事情:
if (!isNaN(array[i].substr(0, 1))) {
array.slice(0,0); //here I want to remove the element whose first character is a number and not a letter - should I use pop?
}
有人可以提供建议吗?提前谢谢。
以下是一个例子:
array[0] ="adkfjdkjfdkj"
array[1] = "12fjkdjfkd"
array[2] = "kcnvmcvn"
因此对于array []的那些元素,我想检查所有三个并删除数组[1],因为第一个字符是整数;然后array [2]将成为数组[1]。我认为类似于pop()的方法在这里很有用
答案 0 :(得分:3)
嘿下面的代码将适合你
var myArray = ['1murli', 'krishna', 'cat', 'dog'];
function checkNumber(array)
{
for (var i = 0; i < array.length; i += 1) {
if (!isNaN(array[i].charAt(0))) {
array.splice(i,1); //removes element which has number at 1st place in array
}
}
console.log(array);
}
checkNumber(myArray);
答案 1 :(得分:1)
在数组上向前迭代(即从0到长度)的问题是,如果你拼接一个成员,你将跳过以下成员(例如,如果你拼接索引5,那么6变成5而下一个你要访问的成员是新的6,这是7,依此类推。)
要解决此问题,请使用 while 循环向后遍历数组:
var i = arr.length;
var re = /^\d/;
while (i--) {
if (re.test(arr[i])) arr.splice(i, 1);
}
您也可以使用ES5 filter,但会创建一个新数组。
答案 2 :(得分:0)
这样的事可能适合你。
var dataArray = ["test", "1test", "something", "2something"];
// Loop the characters.
for (index in dataArray) {
// Get the first character of the current element.
var character = dataArray[index].substr(0, 1);
// Output "yes" if it's a number, otherwise "no"
console.log(isNaN(character) ? 'yes' : 'no');
}
这是一个展示这个概念的JSFiddle。 https://jsfiddle.net/okeujerx/
答案 3 :(得分:0)
对于正向删除,您可以使用此
var array=[];
array[0] ="adkfjdkjfdkj"
array[1] = "12fjkdjfkd"
array[2] = "kcnvmcvn";
array[3] = "kcnvmcvn2";
array[4] = "43kcnvmcvn";
array[5] = "75kcnvmcvn";
array[6] = "cvn";
array[7] = "cvn2";
array[8] = "2cvn";
array[9] = "cvn3";
var indexes=[];
for(var i in array){
var val = array[i].charAt(0);
if(/^\d+$/.test(val)){
indexes.push(i);
}
}
console.log("Indexes to be removed :"+indexes);
console.log("Array before: "+array);
var count =0;
for(var i in indexes){
var indexToBeRemoved = indexes[i]-count;
array.splice(indexToBeRemoved, 1);
count++;;
}
console.log("Array after: "+array);
<强>输出强>
Indexes to be removed :1,4,5,8
Array before: adkfjdkjfdkj,12fjkdjfkd,kcnvmcvn,kcnvmcvn2,43kcnvmcvn,75kcnvmcvn,cvn,cvn2,2cvn,cvn3
Array after: adkfjdkjfdkj,kcnvmcvn,kcnvmcvn2,cvn,cvn2,cvn3
答案 4 :(得分:0)
使用.filter
方法可能是个好主意:
var filtered = array.filter(function(item){
var re = /^\d/;
return !re.test(item);
});