如果键与underscore.js匹配,则比较两个数组

时间:2012-08-01 08:22:40

标签: javascript underscore.js

我有一个拥有Facebook权限的数组,以及用户应该提供的权限数组:

window.FB.api('/me/permissions', function(perm){                     
    if(perm){
       var given_permissions =  _.keys(perm['data'][0];
       var needed_permissions = ["publish_stream", "email"];
       //now check if given permissions contains needed permissions
    }
}

现在我想比较所有needed_permissions是否在given_permissions中,以下划线的方式(不自行循环两个数组并比较值)。我看到了_.include方法,但这会将数组与值进行比较。如果所有权限都可用,我想返回true,否则返回false。如果可能的话,我正在寻找一个不错的单线电话。

原因是,即使用户选择取消扩展权限,FB.login也会返回true。所以我需要对此进行双重检查。

3 个答案:

答案 0 :(得分:18)

您可以使用_.difference查看从您所需的权限中删除给定的权限是否会留下任何后果:

var diff = _(needed_permissions).difference(given_permissions)
if(diff.length > 0)
    // Some permissions were not granted

这样做的一个很好的副作用是你在diff中获得了缺失的权限,以防你想告诉他们什么是错的。

答案 1 :(得分:5)

这个怎么样?

_.all(needed_permissions, function(v){
    return _.include(given_permissions, v);
});

答案 2 :(得分:0)

迟到的答案,但这对我有用:public class MainActivity extends Activity { private AQuery aq; private String serverParameter = ""; private TextView myTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTextView = (TextView)findViewById(R.id.myTextView); aq = new AQuery(this); asyncCall(); myTextView.setText(serverParameter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void asyncCall(){ String url = "http://tryourweb.altervista.org/LocalOfferte0.0/src/category_controller.php"; Map<String, String> params = new HashMap<String, String>(); params.put("type", "get_all"); aq.ajax(url, params, JSONArray.class, new AjaxCallback<JSONArray>() { @Override public void callback(String url, JSONArray json, AjaxStatus status) { if(json != null){ //successful ajax call, show status code and json content try { Toast.makeText(aq.getContext(), status.getCode() + ":" + json.getJSONObject(0).getString("Name"), Toast.LENGTH_LONG).show(); serverParameter = json.getJSONObject(0).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ //ajax error, show error code Toast.makeText(aq.getContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show(); } } }); } }