首页 > 解决方案 > 如何检查对象值是否等于数组中的字符串?

问题描述

我正在制作一个音乐写作网站,我想知道如何检查数组中的对象和字符串是否相等。我想要的结果是 qnoteC 附加到 b1b1。这是我的代码。底部的线是我需要解决的。

const notesarray = ['C','Db','D']
const input = document.getElementById('chordsinput')
const b1b1 = document.querySelector('.b1b1')
const b1b2 = document.querySelector('.b1b2')
const b1b3 = document.querySelector('.b1b3')
const b1b4 = document.querySelector('.b1b4')
const qnoteC = document.createElement('img')
const qnoteDb = document.createElement('img')
const qnoteD = document.createElement('img')

//C
qnoteC.src = 'quarternote.png'
qnoteC.style.width = '32px'
qnoteC.style.position = 'relative'
qnoteC.style.bottom = '8px'
//Db
qnoteDb.src = 'quarternoteflat.png'
qnoteDb.style.width = '32px'
qnoteDb.style.position = 'relative'
qnoteDb.style.bottom = '61px'
//D
qnoteD.src = 'quarternote.png'
qnoteD.style.width = '32px'
qnoteD.style.position = 'relative'
qnoteD.style.bottom = '110px'


generate.addEventListener('click', generateclick)


function generateclick(){
index = notesarray.indexOf(chordsinput.value)
if(index >= 0 )
fifth = notesarray[index + 7]
if(fifth == undefined){
fifth = notesarray[index - 5]}

if(fifth == notesarray[0]){
b1b1.appendChild(qnoteC)
}

标签: javascripthtmlarraysappend

解决方案


我不完全理解你的问题,但我相信你可以检查一下是否array[0] == string很好。如果您需要根据对象检查对象或根据数组检查数组,只需遍历该对象/数组并检查当前元素是否等于另一个对象/数组中的当前元素。


推荐阅读