_.taketWhile方法用於創建數組的一個切片,在數組中從頭開始獲取元素。同樣,將采用這些元素,直到謂詞錯誤返回為止。
用法:
_.takeWhile(array, [predicate=_.identity])
參數:該方法接受上述和以下所述的兩個參數:
- array:此參數保存要查詢的數組。
- [謂詞= _。identity]:此參數保存每次迭代調用的函數。
返回值:此方法用於返回數組的切片。
範例1:在這裏,const _ = require(‘lodash’)用於將lodash庫導入文件中。
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
var users = [
{ 'user':'jupiter', 'active':false },
{ 'user':'mercury', 'active':false },
{ 'user':'saturn', 'active':true }
];
// Use of _.takeWhile()
// method
let gfg = _.takeWhile(users, function(o) { return !o.active; });
// Printing the output
console.log(gfg);
輸出:
[{ user:'jupiter', active:false }, {user:'mercury', active:false}]
範例2:
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
var users = [
{ 'user':'jupiter', 'active':false },
{ 'user':'mercury', 'active':false },
{ 'user':'saturn', 'active':true }
];
// Use of _.takeWhile()
// method
// The `_.matches` iteratee shorthand.
let gfg = _.takeWhile(users, { 'user':'jupiter', 'active':false });
// Printing the output
console.log(gfg);
輸出:
[{ user:'jupiter', active:false }]
範例3:
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
var users = [
{ 'user':'jupiter', 'active':false },
{ 'user':'mercury', 'active':false },
{ 'user':'saturn', 'active':true }
];
// Use of _.takeWhile()
// method
// The `_.matchesProperty` iteratee shorthand.
let gfg = _.takeWhile(users, ['active', false]);
// Printing the output
console.log(gfg);
輸出:
[{ user:'jupiter', active:false }, {user:'mercury', active:false}]
範例4:
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
var users = [
{ 'user':'jupiter', 'active':false },
{ 'user':'mercury', 'active':false },
{ 'user':'saturn', 'active':true }
];
// Use of _.takeWhile()
// method
// The `_.property` iteratee shorthand.
let gfg = _.takeWhile(users, 'active');
// Printing the output
console.log(gfg);
輸出:
[]
注意:該代碼在常規JavaScript中不起作用,因為它需要安裝庫lodash。
相關用法
- Lodash _.take()用法及代碼示例
- Lodash _.last()用法及代碼示例
- Lodash _.nth()用法及代碼示例
- Lodash _.min()用法及代碼示例
- Lodash _.zip()用法及代碼示例
- Lodash _.every()用法及代碼示例
- Lodash _.add()用法及代碼示例
- Lodash _.xor()用法及代碼示例
- Lodash _.max()用法及代碼示例
- Lodash _.pullAll()用法及代碼示例
- Lodash _.unzip()用法及代碼示例
- Lodash _.pullAt()用法及代碼示例
- Lodash _.zipObjectDeep()用法及代碼示例
- Lodash _.groupBy()用法及代碼示例
- Lodash _.findLast()用法及代碼示例
- Lodash _.pull()用法及代碼示例
- Lodash _.indexOf()用法及代碼示例
- Lodash _.isSymbol()用法及代碼示例
- Lodash _.uniqBy()用法及代碼示例
- Lodash _.drop()用法及代碼示例
注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 Lodash _.takeWhile() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。