javascript - 使用循环返回子集

标签 javascript arrays string

这段代码是我写的

function sub (str, start, end) {
    var newstr = ''
    for(var i = 0; i < str.length; i++) {
      if(i >= start && i < end) {
       newstr += str[i]
      }
    }
    return newstr
}

我期望 ('abcd',0,10) 的输出为 'ab',但实际输出为 'a'

最佳答案

如果您的目标是获得一个采用开始和结束索引来返回子字符串的函数,那么您可以在字符串上使用 slice 函数。

var word = 'ascsjdksjdnc';
word.slice(2, 4);
// Output: 'cs'

关于javascript - 使用循环返回子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55330842/

相关文章:

javascript - 单击我需要在该特定行的下一列中添加图像的复选框

javascript - 如何将自定义 Google 搜索添加到我的自定义搜索框?

java - 将字符串拆分为数组

javascript - 登录按钮和身份验证在 Internet Explorer 中不起作用

java - 创建一个数字数组而不循环?

python - 从二叉树中删除一个节点及其所有子节点,而不使用树数据结构

javascript - 在 Javascript 中按值给出一系列目标的排名分数

c - 错误: result of comparison against a string literal is unspecified (use strncmp instead) and Check50 showing error on credit problem

python - 清理 .txt 并计算最常用的单词

javascript - jquery 在车速表中移动指针图像