当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why is this function returning undefined but not loggin in console?

问题描述:

function getIcon(id) {

var icons = {

'i8' : 'nachos1',

'i4' : 'eggs',

'i6': 'glass2',

'i5': 'drink',

'i1': 'starter',

'i2': 'steak',

'i3': 'ice-cream2',

'i10': 'carrot',

'i9': 'bread',

'i7': 'pizza',

'i11' : 'salad'

};

console.log('getIcon'); /* Wont happen */

return 'icon-'+icons[id];

}

$app = {

init: function() {

$el = $('div.el');

console.log($el.data('id')); /* i5 */

var icon = getIcon[$el.data('id')];

console.log(icon); /* undefined */

$el.text(icon);

}

}

$(function(){

$app.init();

})

div {

border: 1px solid;

display:inline-block;

margin:50px;

height: 40px;

min-width: 200px;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

(it should be 'icon-drink')

<div class="el" data-id="i5"></div>

网友答案:

Swap the square brackets for parentheses:

getIcon[$el.data('id')] should be getIcon($el.data('id'))

Square brackets are for property access; parentheses are for function calls.

网友答案:

The getIcon is not an array/object, but you refer it as such:

getIcon[$el.data('id')]

Change it to

getIcon($el.data('id'))
网友答案:

Swap the Square Brackets to round Brackets

getIcon[$el.data('id')]

Change To

getIcon($el.data('id'))
分享给朋友:
您可能感兴趣的文章:
随机阅读: