【问题标题】:Replacing every item at i with j value in an array with JavaScript用 JavaScript 用数组中的 j 值替换 i 处的每个项目
【发布时间】:2020-08-31 10:38:36
【问题描述】:

这里更新的是沙盒中工作副本的链接:

https://codesandbox.io/s/3pkzc

所以我正在尝试运行此代码 - 尝试使用 DOM 获取索引 .href 值并替换它。
但我被困在用值[i] 索引实际替换值[j] 索引的最后一部分。
我试图推动它,因为它是一个数组并研究了其他方法,但我对此一无所知。

// Get the URL of the big red button
const bigRedbtn = document.querySelectorAll('.bigRed');
//Convert into an array
const bigRedbtnArray = Array.from(bigRedbtn);
//Get all the links 
const bookTitles = document.querySelectorAll('.wp-show-posts-entry-title a');
console.log(bookTitles.length);
//Convert into an array
const bookTitlesArray = Array.from(bookTitles);
console.log(bookTitlesArray.length);

for (var i = 0; i < bigRedbtnArray.length; i++) {
    for (var j = 0; j < bookTitlesArray.length; j++) {

        //  what is the links for the book?
        const link = bigRedbtnArray[i].href;
        console.log(link);
        // console.log('bigRedbtn: ', bigRedbtn[i].href);

        //this is the title url to be replaced with the link from bigRedBtn
        const titleLink = bookTitlesArray[j].href;
        console.log(titleLink);

        //So can you do something like this

        //This is where I am stuck at
        //I need to replace each bookTitlesArray[j].href with the value of bigRedbtnArray[i].href

    }
}

【问题讨论】:

  • 您的相关 HTML 在哪里?请为您的问题添加一个完整的工作 sn-p。
  • 两个Array.from() 调用都是不必要的。您可以像在数组 (bigRedbtn[0]) 中一样访问 NodeList 中的元素,或者使用 .length 获取列表的长度。您还可以使用 NodeList.prototype.forEach() 来遍历列表中的元素:bigRedbtn.forEach((element, index) =&gt; { ... })
  • 能否请您添加一个minimal reproducible example 并附上对需求的实际描述,因为我不太明白为什么会有两个循环。
  • “我需要将每个bookTitlesArray[j].href 替换为bigRedbtnArray[i].href 的值” — 预期的结果是什么?每个bookTitlesArray[j].href 相对于每个bigRedbtnArray[i].href 应该是什么样子?推入数组如何帮助替换?
  • 感谢 cmets,Andreas,我确实尝试使用 forEach,但必须创建两个 forEach 函数,但后来卡在了替换部分。例如,我知道如何像 bigRedBtn[0].href = "www.bbc.co.uk" 那样做,但这只是我想为所有按钮做的那个。谢谢!

标签: javascript arrays algorithm


【解决方案1】:

S 我在 Reddit 上问过,这是我得到的答案:

const bigRedbtn = document.querySelectorAll('a.bigRed');
const bookTitles = document.querySelectorAll('.wp-show-posts-entry-title');
bigRedbtn.forEach((n, i) => n.href = bookTitles[i].href)

感谢所有帮助过的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2019-04-19
    • 2012-10-20
    • 2017-12-09
    • 2022-12-03
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    相关资源
    最近更新 更多