javascript - js 多字符串

标签 javascript

我正在尝试理解这段代码:

var text = "Hi, my name is Tyler. How are you?";
var myName = "Tyler";
var hits = [];
for (i = 0; i<= text.length; i++) {
  if (text[i] === "T") {
    for (j = i; j = (i + myName.length); j++) {
      hits.push(i);
    }
  }
}

text[i] 的实际含义是什么?对我来说,它似乎是在说“在文本数组中查找 i 元素”。我不明白这一点有两个原因。第一个是 i 元素没有被定义为任何东西。它是说搜索文本“数组”中的每个元素直到它与 T(我名字的第一个字母)匹配吗?其次,为什么它只是一个字符串而将文本表示为数组?文本后面的 [ ] 括号是否意味着它将文本作为数组引用?

如果这个问题没有真正意义,我很抱歉,但我只是对这一切感到很困惑!预先感谢任何能为我回答这个问题的人!

最佳答案

What does text[i] actually mean?

“从text获取属性i。”

<小时/>

find the i element inside the text array

text 是一个字符串,而不是一个数组。

<小时/>

The first one is that the i element is not defined as anything

i 在上一行中定义:

for (i = 0; i<= text.length; i++) {
<小时/>

And second, why is it representing text as an array when it is just a string?

事实并非如此。 [] 不是特定于数组的。

参见Strings: Character access :

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"

关于javascript - js 多字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33233409/

相关文章:

javascript - 简单的 javascript 更改图像不起作用

javascript - 如何使用 jQuery 获取数组,多个 &lt;input&gt; 具有相同的名称

javascript - jsPDF:打印直接创建的 pdf 到打印机设备

javascript - 为什么通过 setAttribute 或直接设置输入值有区别?

javascript - 单词边界的正则表达式,但包括表情符号

javascript - 追加到具有相同类的所有 div 上

javascript - 在页面上多次使用时 iframe 的问题

javascript - 可以直接用setinterval调用clearinterval吗?

javascript - Plotly:基于 GeoJSON 文件创建 map

javascript - 在我的案例中如何解决 'undefined is not a function'