$('#test').submit(function (event) {
var stocks = [
["STI,GOOG/NYSE_STI,SunTrust Banks"],
["AAPL,GOOG/NASDAQ_AAPL,Apple Inc"]
];
var symbol = $("#textbox").val();
var count = 0
for (var i = 0; i < stocks.length; i++) {
if (stocks[i][0][0] == symbol[0]) {
for (var j = 0; j < symbol.length; j++) {
if (stocks[i + j]) {
count++
}
}
}
if (count == symbol.length) {
var company = stocks[i][0]
var companynocomma = company.split(",");
var ticker = companynocomma[0];
var exchange = companynocomma[1];
var name = companynocomma[2];
$('#GDP').append('<li>' + ticker + '</li>');
$('#GDP').append('<li>' + exchange + '</li>');
$('#GDP').append('<li>' + name + '</li>');
}
}
event.preventDefault();
})
此代码的目标是能够在文本框中键入诸如“AAPL”的股票代码,代码将能够在股票数组中找到“AAPL”,然后将数组拆分为三个单独的阵列[AAPL],[GOOG / NASDAQ_AAPL],[Apple Inc]。如何使这段代码有效?
答案 0 :(得分:0)
try this.
var stocks = [
["STI,GOOG/NYSE_STI,SunTrust Banks"],
["AAPL,GOOG/NASDAQ_AAPL,Apple Inc"]
];
var symbol = $("#textbox").val();
for (var i = 0; i < stocks.length; i++) {
if(stocks[i][0].match(symbol)) {
var company = stocks[i][0];
var companynocomma = company.split(",");
var ticker = companynocomma[0];
var exchange = companynocomma[1];
var name = companynocomma[2];
console.log(companynocomma);
$('#GDP').append('<li>' + ticker + '</li>');
$('#GDP').append('<li>' + exchange + '</li>');
$('#GDP').append('<li>' + name + '</li>');
}
}
答案 1 :(得分:-1)
我不明白你为什么要编制你的股票数据,这样你就不得不做那个混乱的迭代和拆分。既然您知道需要通过其股票代码检索股票,为什么不创建一个股票对象,其中符号为关键字?此外,在我看来,这些数据更适合于对象属性,而不是使用单个字符串来保存各种股票属性(股票代码,交易所和名称)。例如:
var stocks = {
'aapl': {
'ticker': 'AAPL',
'exchange': 'GOOG/NASDAQ_AAPL',
'name': 'Apple Inc'
},
'sti': {
'ticker': 'STI',
'exchange': 'GOOG/NYSE_STI',
'name': 'SunTrust Banks'
}
};
通过这种方式,获得您的库存及其属性变得更加简化:
var stock = stocks[$("#textbox").val().toLowerCase()];
if (stock) {
$('#GDP').append('<li>' + stock.ticker + '</li>');
$('#GDP').append('<li>' + stock.exchange + '</li>');
$('#GDP').append('<li>' + stock.name + '</li>');
}