javascript for() 循环、split() 和数组问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1882492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:44:15  来源:igfitidea点击:

javascript for() loop, split(), and array question

javascriptarrayssplitfor-loop

提问by Jared

Ok I've been asking alot of JS questions lately, and realized I just need to go learn it.

好吧,我最近一直在问很多 JS 问题,并意识到我只需要去学习它。

Been following tutorials at http://www.tizag.com/javascriptTvery simple and straightforward.

一直在http://www.tizag.com/javascriptT 上学习教程,非常简单明了。

I just want to make sure I understand this correctly. It took me a while to get it:

我只是想确保我正确理解这一点。我花了一段时间才得到它:

<script type="text/javascript">
var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

-

——

var myString = "zero one two three four";

Obviously that creates a simple string variable.

显然,这会创建一个简单的字符串变量。

var mySplitResult = myString.split(" ");

That splits it using " " as the delimeter, and assigns it to the mySplitResult array. Correct? Or is it not an array?

使用“”作为分隔符将其拆分,并将其分配给 mySplitResult 数组。正确的?或者它不是一个数组?

for(i = 0; i < mySplitResult.length; i++){

Is this saying the number of values in the array? Doesn't seem like it could be saying the actual length of characters in the string.

这是说数组中的值的数量吗?似乎不能说字符串中字符的实际长度。

document.write("<br /> Element " + i + " = " + mySplitResult[i]); 

This just returns mySplitResult[i] variable "i". Since i is increasing with each loop, it pulls the correct information from the array.

这只是返回 mySplitResult[i] 变量“i”。由于 i 在每个循环中都在增加,因此它会从数组中提取正确的信息。

回答by Tim Down

Your understanding is essentially correct. One thing you should do is declare all your variables: this is particularly important inside functions. So, you should declare ias a variable, either before the loop:

你的理解基本上是正确的。您应该做的一件事是声明所有变量:这在函数内部尤其重要。因此,您应该i在循环之前声明为变量:

var i;
for (i = 0; i < mySplitResult.length; i++) {

... or in the first expression in the forstatement:

... 或在for语句的第一个表达式中:

for (var i = 0; i < mySplitResult.length; i++) {

回答by James Black

Your analysis is correct, but you should see that by just testing it. Use Firebug extension with Firefox and you can step through your javascript.

您的分析是正确的,但您应该通过测试来了解这一点。将 Firebug 扩展与 Firefox 一起使用,您可以逐步完成您的 javascript。

This will help you understand what is going on, as you can then look at properties of the element and monitor what is actually happening.

这将帮助您了解正在发生的事情,因为您可以查看元素的属性并监控实际发生的情况。