正确实现字符串“in”的更好方法是大批

发布于 2024-11-28 05:56:23 字数 502 浏览 2 评论 0原文

假设您有一个包含 ActionScript3 中的多个字符串的数组,并且您想要测试测试字符串是否在该数组“中”。 “in”仅适用于 AS3 中数组的索引(如果你问我的话,这完全是迟缓的),尽管它确实适用于对象,但我们不是在谈论对象。

有人可以改进(减少)我现在使用的这段代码吗?我希望避免定义实用函数 - 我想要一个漂亮优雅的单行代码。

myArray.filter(function(item:*, i:int, a:Array) { return (item == testString); }).length

由于 0 == false 我们可以在测试中使用它。请注意,testString 的范围是在包含函数中定义的,并由闭包封装。

if (allowedProfiles.filter(function(item:*, i:int, a:Array) { return (item == name); }).length){ // yay! }

suppose you have an array with a number of strings in ActionScript3 and you want to test if a test string is "in" that array. "in" only works against the index with Arrays in AS3 (which is totally retardo if you ask me), though it does work with ojects, but we're not talking about objects.

Can someone improve (reduce) on this code I'm using now? I'm hoping to avoid defining a utility function - I'd like a nice elegant one-liner.

myArray.filter(function(item:*, i:int, a:Array) { return (item == testString); }).length

Since 0 == false we can use it in a test. Do note that testString's scope is defined in the containing function, encapsulated by the closure.

if (allowedProfiles.filter(function(item:*, i:int, a:Array) { return (item == name); }).length){ // yay! }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掩于岁月 2024-12-05 05:56:23

使用Array.indexOf()方法可以看到字符串在数组中的索引不是-1(未找到):

var myArray:Array = ["hello", "world"];
trace(myArray.indexOf("hello")); // == 0;
trace(myArray.indexOf("goodbye")); // == -1

Use the Array.indexOf() method to see that the index of the string in the array is not -1 (not found):

var myArray:Array = ["hello", "world"];
trace(myArray.indexOf("hello")); // == 0;
trace(myArray.indexOf("goodbye")); // == -1
草莓酥 2024-12-05 05:56:23

为什么不直接使用 indexOf()?

if(myArray.indexOf("testString") != -1) { // it's in there 

Why not just use indexOf()?

if(myArray.indexOf("testString") != -1) { // it's in there 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文