提示和用于循环的值不起作用的值

发布于 2025-02-05 12:36:06 字数 725 浏览 4 评论 0原文

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文