javascript - 如何在javascript中找到没有内置函数的子字符串?
问题描述
我正在尝试重建 Substring 函数。这是我的代码。当传递单个参数以及 num1> num2 时它不起作用。谁能告诉我应该在哪里更改?
这是我的代码......
function myFunction(num1, num2) {
var str = "This is a string";
var subString = "";
var len = str.length;
if (num1 < 0 || num2 > len) {
console.log("Invalid input");
} else {
var k = 0;
for (i = num1; i < num2; i++) {
subString = subString + str[i];
k++;
}
console.log(subString);
}
}
myFunction(0, 4);
解决方案
You could start with a proper function name and singnature by using the string, start and end index as parameters.
Then start with an empty string and iterate from start to the end or the length of the string.
function substring(string, start, end) {
var result = '',
length = Math.min(string.length, end),
i = start;
while (i < length) result += string[i++];
return result;
}
console.log(substring('This is a string', 0, 4));
console.log(substring('This is a string', 40, 4));
推荐阅读
- angular - 尝试使用 REST 服务时,离子屏幕变为空白
- webpack - 更改 Vue 构建 dist 文件前缀
- node.js - 无法使用 WebSocket 连接到 node.js 检查器
- windows - 我的静音麦克风脚本不起作用,需要想法和答案
- css - 无法通过 Symfony 项目中的 css 内容属性设置 png 图像
- angular - 页面加载时,角度值更改多次调用
- javascript - Vue.js 组件不相互独立
- python - 迭代器应该返回字符串,而不是使用 csv.reader 列出错误
- d3.js - d3.js: Hierarchical Edge Bundling分别为每个链接改变curveBundle
- nginx - Nginx的配置文件nginx.conf是静态加载还是动态加载?