英文:
I want to sum up all the integers using js loop. In my given case correct answer is 6. How can i do this using Js?
问题
<span class="gap">1</span>
<span class="gap">2</span>
<span class="gap">1</span>
<span class="gap">2</span>`
var arr = []
var sum = 0;
for (i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
我尝试使用上面的代码,但无法将数组中的所有整数相加...
英文:
<span class="gap">1</span>
<span class="gap">2</span>
<span class="gap">1</span>
<span class="gap">2</span>`
var arr = []
var sum = 0;
for (i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
i was trying to do it by above code but i am unable to add all the integers in the array...
答案1
得分: 0
然后,您应该从HTML中提取值。
然后,您应该将它们转换为数字并相加。
我编写这段代码的前提是没有其他具有 class="gap"
的元素;否则,您应该编写父元素选择器,而不是 document
。
let gapsElements = document.querySelectorAll('.gap');
let sum = 0;
for (i = 0; i < gapsElements.length; i++) {
const gapValueInt = +gapsElements[i].innerText; // 前面的 '+' 号将字符串转换为数字;
sum += gapValueInt;
}
console.log(sum);
我替换了前缀以使其更标准,并删除了 array
变量,因为我们不需要它。
英文:
First you should extract the values from HTML.
Then you should convert them to numbers and sum.
I wrote this assuming there are no other elements having class="gap"
; otherwise, you should write the parent element selector instead of document
.
let gapsElements = document.querySelectorAll('.gap');
let sum = 0;
for (i = 0; i < gapsElements.length; i++) {
const gapValueInt = +gapsElements[i].innerText; // the '+' before 'arr' will convert a string to number;
sum += gapValueInt;
}
console.log(sum);
I replaced prefixes to be more standart, and removed array
var, as we don't need it.
答案2
得分: 0
如果我理解你的问题,你可以使用Document.getElementsByClassName()
来获取匹配的span
元素,然后迭代这些元素并调用parseInt()
如下所示:
var arr = document.getElementsByClassName("gap");
var sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += parseInt(arr[i].textContent);
}
console.log(sum);
<span class="gap">1</span>
<span class="gap">2</span>
<span class="gap">1</span>
<span class="gap">2</span>
英文:
If I understand your question, you can use Document.getElementsByClassName()
to get the matching span
(s) then iterate those and call parseInt()
like,
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var arr = document.getElementsByClassName("gap");
var sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += parseInt(arr[i].textContent);
}
console.log(sum);
<!-- language: lang-html -->
<span class="gap">1</span>
<span class="gap">2</span>
<span class="gap">1</span>
<span class="gap">2</span>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论