我跑:
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
我得到的数组如下:
["27","-","28","August","663","CE"]
如何迭代该数组并循环它以查找对象是文本字符串还是数字?
答案 0 :(得分:0)
DIR 01;34;47
以123的价值 console.log(!isNan(Number(words [i]))&amp;&amp; words [i]!==''); //使用Number的csadner解决方案 //如果字符串是数字,则所有上述日志都将输出true }
这应该可以解决问题。这里发生了什么:
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
console.log(/\d+/g.test(words[i])); // RegExp way (possible only with input formatted like string you specified)
console.log(/^[\d]+(.[\d]+)*$/g.text(words[i])); // RegExp way that would consider floats, ints as a number and would not consider strings like "123aaa" as a number
console.log(!isNaN(parseInt(words[i]))); // NaN with parseInt way
console.log(!isNaN(words[i])); // only NaN way - warning: strings like "123aaa" are considered as a number as parseInt would create an int
,因此我们检查返回的值是否不是NaN。答案 1 :(得分:0)
您可以在$.isNumeric()
循环
$.each
$.each(words,function(){
if($.isNumeric(this)) {
//code to execute if number
}
})
答案 2 :(得分:0)
在您已有的for
循环中,您可以确定它是否不是具有此条件的数字:
!words[i] || isNaN(words[i])
如果是true
,那么它不是数字
答案 3 :(得分:0)
您可以直接使用Number()
var arr = ["0","-","28","August","663","CE"]
function isNumber(str) {
return str && isNaN(Number(str)) ? false : true
}
arr.forEach((item) => {
console.log(isNumber(item))
})
答案 4 :(得分:0)
您可以使用Number()
,如果字符串是非数字,则返回NaN
。要记住的一件事是Number('') === 0
。
for (const word of words.split(' ')) {
if (isNaN(Number(word)) {
//code if non-numeric
}
else {
//code if numeric
}
}
答案 5 :(得分:0)
完全正确,这些都是类型字符串,因为它们在引号之间。我想你想知道这些字符串是否可以转换为数字。您可以使用isNan()进行检查,数字时为false,否则为true。您实际上可以使用parseInt();
将字符串转换为数字(整数)
var array = ["27","-","28","August","663","CE"];
for (var el of array) {
if(!isNaN(el)) { // check if el is numeric
el = parseInt(el); // parse el to a int
console.log("This element is numeric");
console.log(el);
}
}