简体   繁体   English

如何防止 javascript 中的值被转换为字符串?

[英]How to prevent values from being converted to strings in javascript?

    var str;
    var displayedNum;
    for (i in imgURLArray){
        str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
        $("ul.selection-list").append(str);

}

I need to do this within a loop, but what happens is it prints out "11" instead of "2", because it converts to string before addition.我需要在一个循环中执行此操作,但会打印出“11”而不是“2”,因为它在添加之前转换为字符串。

I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.如果我尝试在字符串之外进行加法并将其存储在变量中,我也会遇到同样的问题,它仍然会转换为字符串而不是进行加法。

Number(1+1) still converts to string first before turning it into a number, so it comes out 11. Number(1+1) 在变成数字之前仍然先转换为字符串,所以结果是 11。

Use parenthesis:使用括号:

var str = "foobar" + (1+i) + "other stuff";

I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.如果我尝试在字符串之外进行加法并将其存储在变量中,我也会遇到同样的问题,它仍然会转换为字符串而不是进行加法。

It should not.它不应该。 My guess is that you are doing something wrong there too.我的猜测是你在那里也做错了什么。

Update: It seems you are converting i to a string somewhere in the code you did not post.更新:您似乎正在将i转换为您未发布的代码中某处的字符串。

Update 2: Don't use for..in to loop over an array .更新 2: 不要使用for..in循环数组 Use a normal for loop if it is really an array:如果它确实是一个数组,请使用普通for循环:

for(var i = 0, l = imgURLArray.length; i < l; i++)

But if it is an objects:但如果它是一个对象:

for...in will always set i as a string (as it loops over the properties of the object which are not always integers). for...in将始终将i设置为字符串(因为它循环遍历 object 的属性,这些属性并不总是整数)。 That means you would have to convert i before you do any addition:这意味着您必须在进行任何添加之前转换i

... + (1 + (+i)) + ...

Update 3:更新 3:

You don't always have to use such an "explicit" for loop.您不必总是使用这种“显式”的 for 循环。 For example, you can traverse the array in reverse order, which makes the head shorter:例如,您可以以相反的顺序遍历数组,这使得头部更短:

for (var i = imgURLArray.length; i--; ) {
    str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
    $("ul.selection-list").prepend(str);
}

Try wrapping numbers in Number()尝试在 Number() 中包装数字

Like:喜欢:

var i = 1;

var str = "foobar" + Number(1+i) + "other stuff";
var str = "foobar" + (1+i) + "other stuff";

You could just use the parseInt method:您可以只使用 parseInt 方法:

var str = "foobar" + (parseInt(1+i)) + "other stuff";

The reason is due to your loop:原因是由于您的循环:

for (i in imgURLArray){

This iterates over all the property names of imgURLArray as strings.imgURLArray的所有属性名称作为字符串进行迭代。 So you will need to use Number() to convert i to an integer:因此,您需要使用Number()i转换为 integer:

    str = "<li photonum="+i+">" + "<a>"+ (1+Number(i)) + "</a>" + "</li>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM