How to push item to [string] in TypeScript

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

I want to add items to [string]. But the following code fails at param.push statement.

EDIT

declare var sqlitePlugin:any; var query: string = `SELECT * FROM items `;  var param: [string];  if (options['limit']) {   var limit = options['limit'];   query = query + " LIMIT ? ";   param.push(String(limit)); }  if (options['offset']) {   var offset = options['offset'];   query = query + " OFFSET ? ";   param.push(String(offset)); }  sqlitePlugin.openDatabase({name: 'Items.db', key: 'Password', location: 'default'}, (db) =>  {   db.transaction((tx)=> {     tx.execQuery(query, param, (resultSet)=>{     this.items = [];       for(let i = 0; i < resultSet.rows.length; i++) {         var item: Item = new Item();         item.code = resultSet.rows.item(i).item_code;         item.name = resultSet.rows.item(i).item_name;         this.items.push(item);       }       callback(this.items);     } );   } }); 

Sorry to ask this very basic question but I'm struggling for 2 days.. Please give me any hint or link.

Thanks in advance.

回答1:

Try:

var param: string[] = []; 

Check this snippet out, it shows the desired result. The issue is you're just not initialising the variable param, so .push doesn't exist for undefined.

Also you weren't declaring the array properly (see difference above). There are two ways to do so, taken from TypeScript's documentation:

TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type:

let list: number[] = [1, 2, 3]; 

The second way uses a generic array type, Array:

let list: Array<number> = [1, 2, 3]; 

And here is the relevant documentation on TS site



回答2:

You can use either of the below 2 syntaxes to define a string array in typescript:

Using general array syntax:

var param: string[] = []; 

Using Generics syntax:

var param: Array<string> = []; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!