2017-07-30 96 views
0

考虑以下几点:创建`option`用下划线

function autoCompleteOptions(json) { 
 
     _.map(json, function(x) { 
 
      const a = x["a"]; 
 
      const b = x["b"]; 
 
      var option = document.createElement('option'); 
 
      option.setAttribute('data-value', a); 
 
      option.value = b; 
 
      console.log('option:', option); 
 
      return option; 
 
     }) 
 
    } 
 

 
var result = autoCompleteOptions([ 
 
    { 
 
     "a" : "hi", 
 
     "b" : "world" 
 
    } 
 
    ]); 
 

 
console.log('result:', result);
<script src="http://underscorejs.org/underscore-min.js"></script>

为什么console.log显示undefined?我期待着一组option HTML元素。

+2

因为你的函数('autoCompleteOptions')没有明确返回值? – undefined

+0

在你的代码片段中,它看起来像你不包含'underscore.js' –

+0

这段代码中没有JSON。 JSON是一种将数据编码为字符串的格式。你有一个数组和一个对象。 – 4castle

回答

1

我认为你需要从你的函数

return _.map(json, function(x) {...} 
0

这仅仅是与#2是如何工作的问题返回_.map结果。您正尝试从非安全来源加载_库(http://underscorejs.org/underscore-min.js),但SO使用https

从像https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js这样的安全来源加载它来修复_未定义的问题。

作为第二个问题,正如其他人指出的那样,您需要返回autoCompleteOptions函数中的某些内容。

function autoCompleteOptions(json) { 
 
    return _.map(json, function(x) { 
 
    const a = x["a"]; 
 
    const b = x["b"]; 
 
    var option = document.createElement('option'); 
 
    option.setAttribute('data-value', a); 
 
    option.value = b; 
 
    console.log('option:', option); 
 
    return option; 
 
    }) 
 
} 
 

 
var result = autoCompleteOptions([{ 
 
    "a": "hi", 
 
    "b": "world" 
 
}]); 
 

 
console.log('result:', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>