如何在 TypeScript 中将项目推送到 [string]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37460704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:31:40  来源:igfitidea点击:

How to push item to [string] in TypeScript

javascripttypescript

提问by tmrex7

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

我想将项目添加到 [string]。但是以下代码在 param.push 语句中失败。

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.

很抱歉问这个非常基本的问题,但我挣扎了 2 天.. 请给我任何提示或链接。

Thanks in advance.

提前致谢。

回答by gdgr

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 .pushdoesn't exist for undefined.

检查此代码段,它显示了所需的结果。问题是你只是没有初始化变量param,所以.push不存在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 的文档:

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:

TypeScript 与 JavaScript 一样,允许您使用值数组。数组类型可以用两种方式之一编写。首先,使用元素类型后跟 [] 来表示该元素类型的数组:

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

The second way uses a generic array type, Array:

第二种方式使用泛型数组类型 Array:

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

And here is the relevant documentation on TS site

这是 TS 网站上的相关文档

回答by Aditya Singh

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> = [];