Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

javascript - Dictionary returns undefined when searching by key

I am currently making a small, test website, and I have a function that will add an image to the innerHTML based on the input:

function montreImg(nomImage){
var output = document.getElementById("fileContent"/*Placeholder*/);

var images = {
    ranch : "/ressources/bungalow/ranch.jpg",
    bungalowstyle : "/ressources/bungalow/bungalow style.jpg",
    tuscan : "/ressources/bungalow/tuscan.jpg",
    farmhouse : "/ressources/bungalow/farmhouse.jpg",
    traditional1 : "/ressources/bungalow/traditional1.jpg",
    cabin : "/ressources/2etages/cabin.jpg",
    craftsman : "/ressources/2etages/craftsman.jpg",
    modern : "/ressources/2etages/modern.jpg",
    southern : "/ressources/2etages/southern.jpg",
    traditional2 : "/ressources/2etages/traditional2.jpg"
};

console.log(images.nomImage);
var img = '<img src="' + images[nomImage] + '">';
output.innerHTML += img;
}

Whenever I search the object by the key, it gives me undefined (in the console log) and it'll say couldn't find the image because it's searching for undefined. I originally had the keys as strings and searched with:

images[nomImage]

but that also returned undefined. I verified, and the input is of type string. I have searched for hours but couldn't find anyone who had a similar problem to me. I am not using AJAX or any other frameworks, it's pure JS and a local website.

I can't seem to find anything wrong with my code, but I am relatively new to JS, so I might be missing something obvious.

Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just found out by copying and pasting the console logs, there was an extra space in front of my input text. This drove me crazy. Sorry for posting, but I'll leave it up in case anyone runs into the same thing as me.

Here's what the input was:

"tuscan "

But it should have been:

"tuscan"

Didn't notice until I copied and pasted outside of the log.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...