提示和用于循环的值不起作用的值
我是JavaScript的初学者,并创建了一个添加数组编号的indeces的程序,将等于给定的目标,并将indeces打印为输出。
例如 - 输入为nums array = [1,2,3,4,5],目标= 9 添加第三&第四个元素将给出目标值(5+4 = 9),因此,
如果我从提示中传递值,则输出为3,4,代码不起作用。但是,如果我直接通过值,则代码正常工作。我不知道为什么会发生这种情况,我缺乏任何概念。请给出您的建议:)
代码如下:
// taking array from user
let nums = [];
let size = 5; // Array size
for (let a = 0; a < size; a++) {
nums[a] = prompt('Enter array Element ' + (a + 1));
}
// taking Sum Target from user
let sum = prompt("Enter the Sum Target");
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === sum) {
alert(`The Two indices are ${i} and ${j}`);
}
}
}
I am Beginner in Javascript, and created a program Adding Indeces of an Array numbers would come equal to the target given, and Printing the indeces as an output.
eg - Input is nums array= [1,2,3,4,5] and target = 9
adding 3th & 4th element would give the target value (5+4=9), so output would be 3,4
If i pass the values from Prompt, the code is not working. However if i pass the values directly, the code is working fine. I do not know why is this happening, is there any concept, that i am lacking. Please give your suggestions :)
Code is Below:
// taking array from user
let nums = [];
let size = 5; // Array size
for (let a = 0; a < size; a++) {
nums[a] = prompt('Enter array Element ' + (a + 1));
}
// taking Sum Target from user
let sum = prompt("Enter the Sum Target");
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === sum) {
alert(`The Two indices are ${i} and ${j}`);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论